# Copyright (c) 2024 The Jaeger Authors.
# SPDX-License-Identifier: Apache-2.0

import json


def generate_spans_markdown_table(v1_spans, v2_spans):
    """
    Generates a markdown table specifically for spans metrics with two main columns V1 and V2.

    Args:
        v1_spans (dict): The dictionary of V1 spans metrics.
        v2_spans (dict): The dictionary of V2 spans metrics.

    Returns:
        str: The generated markdown table as a string.
    """
    table = "### Equivalent Metrics\n\n"
    table += "| V1 Metric | V1 Parameters | V2 Metric | V2 Parameters |\n"
    table += "|-----------|---------------|-----------|---------------|\n"


    # Iterate through the metrics using zip_longest to handle mismatched lengths
    from itertools import zip_longest

    for (v1_metric, v1_params), (v2_metric, v2_params) in zip_longest(v1_spans.items(), v2_spans.items(), fillvalue=('', {})):
        v1_inner_keys = ', '.join(v1_params.keys()) if v1_params else ''
        v2_inner_keys = ', '.join(v2_params.keys()) if v2_params else ''
        table += f"| {v1_metric} | {v1_inner_keys} | {v2_metric} | {v2_inner_keys} |\n"

    return table



def generate_combined_markdown_table(common_metrics, v1_metrics, v2_metrics):
    """
    Generates a markdown table for combined metrics from common, V1, and V2.

    Args:
        common_metrics (dict): The dictionary of common metrics.
        v1_metrics (dict): The dictionary of V1 only metrics.
        v2_metrics (dict): The dictionary of V2 only metrics.

    Returns:
        str: The generated markdown table as a string.
    """
    table = "### Combined Metrics\n\n"
    table += "| V1 Metric | V1 Parameters | V2 Metric | V2 Parameters |\n"
    table += "|-----------|---------------|-----------|---------------|\n"
    for metric_name, params in common_metrics.items():
        v1_params = ', '.join(common_metrics[metric_name].keys()) if params else 'N/A'
        v2_params = ', '.join(common_metrics[metric_name].keys()) if params else 'N/A'
        table += f"| {metric_name} | {v1_params} | {metric_name} | {v2_params} |\n"

    # Then, handle V1-only metrics (V2 shows as N/A)
    for metric_name, v1_params in v1_metrics.items():
            v1_params_str = ', '.join(v1_params.keys()) if v1_params else 'N/A'
            table += f"| {metric_name} | {v1_params_str} | N/A | N/A |\n"

    # Then, handle V2-only metrics (V1 shows as N/A)
    for metric_name, v2_params in v2_metrics.items():
            v2_params_str = ', '.join(v2_params.keys()) if v2_params else 'N/A'
            table += f"| N/A | N/A | {metric_name} | {v2_params_str} |\n"

    return table

class ConvertJson:

    def __init__(self, json_fp, h1):
        self.fp = json_fp
        self.h1 = h1
        self.jdata = self.get_json()
        self.mddata = self.format_json_to_md()

    def get_json(self):
        with open(self.fp) as f:
            res = json.load(f)
        return res

    def format_json_to_md(self):
        text = f'# {self.h1}\n'
        dct = self.jdata

        # Extracting individual metric dictionaries
        common_metrics = dct.get("common_metrics", {})
        v1_only_metrics = dct.get("v1_only_metrics", {})
        v2_only_metrics = dct.get("v2_only_metrics", {})

        # Generate combined table
        combined_metrics_table = generate_combined_markdown_table(
            common_metrics, v1_only_metrics, v2_only_metrics
        )
        
        filtered_v1_metrics = {
       "jaeger_collector_spans_rejected_total": {"debug": "false", "format": "","svc": "","transport":""},
       "jaeger_build_info": {"build_date": "","revision": ""," version": ""}  # Add more metrics as needed
       }

        # Hardcoding filtered v2 metrics
        filtered_v2_metrics = {
       "receiver_refused_spans": {"receiver": "","service_instance_id": "","service_name": "","service_version": "","transport": ""},
       "target_info": {"service_instance_id": "","service_name": "","service_version": ""}  # Add more metrics as needed
        }
        spans_metrics_table = generate_spans_markdown_table(filtered_v1_metrics, filtered_v2_metrics)
        text += combined_metrics_table+spans_metrics_table
        return text

    def convert_dict_to_md(self, output_fn):
        with open(output_fn, 'w') as writer:
            writer.writelines(self.mddata)
        print('Dict successfully converted to md')

# Usage
fn = ''  # Enter the path of the JSON file generated by compare_metrics.py
title = "TITLE"
converter = ConvertJson(fn, title)
converter.convert_dict_to_md(output_fn='metrics.md')